"""
GDP动态图绘制
"""
from pyecharts.charts import Bar,Timeline
from pyecharts.options import TitleOpts, LegendOpts,ToolboxOpts,VisualMapOpts
from pyecharts.options import LabelOpts

# 读取数据
f = open("1960-2019全球GDP数据.csv","r",encoding="GB2312")
lines = f.readlines()
f.close()
# print(lines)
# 去掉第一行表头
lines = lines[1:]

# 将获取的数据处理成需要的格式
data_dict = {}
for line in lines:
    line = line.replace("\n","")
    items = line.split(",")
    year = items[0]
    country = items[1]
    gdp = items[2]
    if year not in data_dict:
        data_dict[year] = {}
    data_dict[year][country] = gdp
# print(data_dict)
# 年份排序
year_list = list(data_dict.keys())
year_list.sort()
# print(year_list)
timeline = Timeline()
for year in year_list:
    country_dict = data_dict[year]
    # print(country_dict)
    # 按照GDP排序，取前10名
    country_list = list(country_dict.items())
    country_list.sort(key=lambda x:float(x[1]),reverse=True)
    top10_country_list = country_list[:10]
    # print(top10_country_list)
    countries = []
    gdps = []
    for item in top10_country_list:
        countries.append(item[0])
        gdps.append(float(item[1])//100000000)
    # print(countries)
    # print(gdps)

    # 生成柱状图
    bar = Bar()
    countries.reverse()
    gdps.reverse()
    bar.add_xaxis(countries)
    bar.add_yaxis("GDP(亿)",gdps,label_opts=LabelOpts(is_show=True,position="right"))
    bar.reversal_axis()# 反转坐标轴
    bar.set_global_opts(
        title_opts=TitleOpts(title=f"{year}年全球GDP前10国家",pos_left="left",pos_top="top",pos_bottom="1%"),
        legend_opts=LegendOpts(is_show=True),
        toolbox_opts=ToolboxOpts(is_show=True),
        visualmap_opts=VisualMapOpts(is_show=True)
    )
    # bar.render(f"{year}年全球GDP前10国家.html")

    # 生成时间线
    timeline.add(bar,year)
timeline.add_schema(
    play_interval=1000,
    is_auto_play=True,
    is_loop_play=True
)
timeline.render("1960-2019年全球GDP前10国家动态柱状图.html")
